﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// ReSharper disable InconsistentNaming

namespace Newbe.TestDirector.Notification.Web.Domain.Impl
{
    public class BugDao : IBugDao
    {
        public delegate BugDao Factory(TestDirectorAcceessDb testDirectorAcceessDb);
        private readonly TestDirectorAcceessDb _testDirectorAcceessDb;
        private readonly IBugTableColumnsFactory _bugTableColumnsFactory;

        public BugDao(TestDirectorAcceessDb testDirectorAcceessDb, IBugTableColumnsFactory bugTableColumnsFactory)
        {
            _testDirectorAcceessDb = testDirectorAcceessDb;
            _bugTableColumnsFactory = bugTableColumnsFactory;
        }

        public IEnumerable<BugData> List()
        {
            using (var conn = _testDirectorAcceessDb.GetConnection())
            {
                var cmd = conn.CreateCommand();
                cmd.CommandText = "select * from BUG";
                conn.Open();
                var dr = cmd.ExecuteReader();
                Debug.Assert(dr != null, nameof(dr) + " != null");
                var geTableColumns = _bugTableColumnsFactory.GeTableColumns();
                var list = conn.Query("select * from BUG").ToArray();
                return list.Select(x =>
                {
                    var dic = ((ICollection<KeyValuePair<string, object>>)x)
                        .ToDictionary(xx => xx.Key, xx => xx.Value);
                    var bugData = new BugData
                    {
                        Id = x.BG_BUG_ID.ToString(),
                        Fields = geTableColumns.Select(col => new BugDataField
                        {
                            TableColumn = col,
                            Value = Convert.ToString(dic[col.ColumnName])
                        }).ToArray()
                    };
                    return bugData;
                }).ToArray();
            }
        }
    }
}
